/**
 * @class SaveLoadEngine
 * @constructor
 */

function unescapeRestData(data) {
    var tempNode = document.createElement('div');
    tempNode.innerHTML = data.replace(/&amp;/, '&');
    return tempNode.innerText || tempNode.text || tempNode.textContent;
}

function getSelectorFromXML(responseXML, selectorName, attributeName, attributeValue) {
    if (responseXML.querySelector) {
        return responseXML.querySelector(selectorName + "[" + attributeName + "='" + attributeValue + "']");
    } else {
        var query = "//" + selectorName + "[@" + attributeName + "='" + attributeValue + "']";
        try {
            return responseXML.selectSingleNode(query);
        } catch (e) {
            alert("浏览器不支持");
            window.stop && window.stop();
            throw "不支持浏览器";
        }
    }
}

function getSubSelectorTextFromXML(responseXML, selectorName, attributeName, attributeValue, subselectorName) {
    var selector = getSelectorFromXML(responseXML, selectorName, attributeName, attributeValue);

    var value = selector.innerText || selector.text || selector.textContent;

    if (!value)
        value = "";

    return value;
}

var ProbandDataLoader = Class.create({
    initialize: function() {
        this.probandData = undefined;
    },
    load: function(callWhenReady) {
        // new Ajax.Request(XWiki.currentDocument.getRestURL('objects/PhenoTips.PatientClass/0.xml').substring(1), {
        //     method: "GET",
        //     onSuccess: this.onProbandDataReady.bind(this),
        //     onComplete: callWhenReady ? callWhenReady : {}
        // });
        this.onProbandDataReady();
    },
    onProbandDataReady: function(response) {
        // var responseXML = response.responseXML;  
        // this.probandData = {};
        // this.probandData.firstName = unescapeRestData(getSubSelectorTextFromXML(responseXML, "property", "name", "first_name", "value"));
        // this.probandData.lastName  = unescapeRestData(getSubSelectorTextFromXML(responseXML, "property", "name", "last_name", "value"));
        // this.probandData.gender    = unescapeRestData(getSubSelectorTextFromXML(responseXML, "property", "name", "gender", "value"));
        // if (this.probandData.gender === undefined || this.probandData.gender == '')
        //     this.probandData.gender = 'U';
        this.probandData = JSON.parse(parent.$("#probandData").val());
        if (this.probandData.gender === undefined || this.probandData.gender == '') {
            this.probandData.gender = 'U';
        }
        console.log("Proband data: " + stringifyObject(this.probandData));
    },
});


var SaveLoadEngine = Class.create({

    initialize: function() {
        this._saveInProgress = false;
    },

    serialize: function() {
        return editor.getGraph().toJSON();
    },

    createGraphFromSerializedData: function(JSONString, noUndo, centerAround0) {
        console.log("---- load: parsing data ----");
        document.fire("pedigree:load:start");

        try {
            var changeSet = editor.getGraph().fromJSON(JSONString);
        } catch (err) {
            console.log("ERROR loading the graph: " + err);
            alert("加载失败");
            document.fire("pedigree:graph:clear");
            document.fire("pedigree:load:finish");
            return;
        }

        if (!noUndo) {
            var probandData = editor.getProbandDataFromPhenotips();
            var genderOk = editor.getGraph().setProbandData(probandData.firstName, probandData.lastName, probandData.gender, probandData.precursor);
            if (!genderOk)
                console.log("先证者性别与初始化数据不匹配。");
            JSONString = editor.getGraph().toJSON();
        }

        if (editor.getView().applyChanges(changeSet, false)) {
            editor.getWorkspace().adjustSizeToScreen();
        }

        if (centerAround0)
            editor.getWorkspace().centerAroundNode(0);

        if (!noUndo)
            editor.getActionStack().addState(null, null, JSONString);

        document.fire("pedigree:load:finish");
    },

    createGraphFromImportData: function(importString, importType, importOptions, noUndo, centerAround0) {
        console.log("---- import: parsing data ----");
        document.fire("pedigree:load:start");
        try {
            console.log(importString);
            console.log(importType);
            console.log(importOptions);
            var changeSet = editor.getGraph().fromImport(importString, importType, importOptions);
            if (changeSet == null) throw "此数据不能创建家系图";
        } catch (err) {
            alert("加载错误: " + err);
            document.fire("pedigree:load:finish");
            return;
        }

        if (!noUndo) {
            var probandData = JSON.parse(parent.$("#probandData").val());
            // console.log(probandData);
            // console.log(probandData.gender);
            if (probandData.sex == "female") {
                probandData.gender = "F"
            } else if (probandData.sex == "male") {
                probandData.gender = "M"
            } else {
                probandData.gender = ""
            };
            var genderOk = editor.getGraph().setProbandData(probandData.firstName, probandData.lastName, probandData.gender, probandData.precursor);
            if (!genderOk)
                console.log("先证者性别与初始化数据不匹配。");
            JSONString = editor.getGraph().toJSON();
        }
        if (editor.getView().applyChanges(changeSet, false)) {
            editor.getWorkspace().adjustSizeToScreen();
        }

        if (centerAround0)
            editor.getWorkspace().centerAroundNode(0);

        if (!noUndo)
            editor.getActionStack().addState(null, null, JSONString);
        editor.getView().siblingSorting();
        document.fire("pedigree:load:finish");
    },
    saveSilence: function(callback) {
        if (this._saveInProgress)
            return;
        editor.getNodeMenu().hide();
        editor.getView().exitHoverMode();
        editor.getView().unmarkAll();

        var me = this;
        me._notSaved = true;
        var jsonData = this.serialize();
        var exportFamilyData = PedigreeExport.exportAsSimpleJSON(editor.getGraph().DG, "all");
        var familyDataToSave = {};
        familyDataToSave.family_data = exportFamilyData;
        familyDataToSave.edit_token = edit_token;
        familyDataToSave.image_data = editor.getWorkspace().getSVGCopy().getSVGText();
        console.log(familyDataToSave);

        var image = $('canvas');
        var background = image.getElementsByClassName('panning-background')[0];
        var backgroundPosition = background.nextSibling;
        var backgroundParent = background.parentNode;
        backgroundParent.removeChild(background);
        var bbox = image.down().getBBox();
        var familyServiceURL = editor.getExternalEndpoint().getSavePedigreeURL();
        jQuery.ajax({
            url: save_url,
            async: false,
            type: "post",
            data: familyDataToSave,
            success: function(res) {
                console.log(res);
                jQuery.each(res.data, function(index, item) {
                    var node = editor.getView().getNode(item.id);
                    node.setMemberID(item.memberID);
                    node = editor.getGraph().getProperties(item.id);
                    node.memberID = item.memberID;
                    editor.getGraph().setProperties(item.id, node);
                    console.log(editor);
                });
                //近亲，调解出现样式跳行问题chen.yuguo start
                jsonStr = JSON.parse(exportFamilyData);
                jQuery.each(jsonStr, function(index, item) { //console.log(item);return false;
                    //名字
                    firstName = item.firstName;
                    if (firstName != undefined) {
                        if (firstName !== '') {
                            editor.getView().getNode(item.id).getGraphics().updateNameLabel();
                        }
                    }
                    //结果评估
                    evaluatedinfo = item.evaluatedinfo;
                    if (evaluatedinfo != undefined) {
                        if (evaluatedinfo !== '') {
                            editor.getView().getNode(item.id).getGraphics().updateEvaluatedInfoLabel();
                        }
                    }
                    //备注
                    comments = item.comments;
                    if (comments != undefined) {
                        if (comments !== '') {
                            editor.getView().getNode(item.id).getGraphics().updateCommentsLabel();
                        }
                    }
                    //癌症：cancerTypes
                    cancerTypes = item.cancerTypes;
                    if (cancerTypes != undefined) {
                        editor.getView().getNode(item.id).getGraphics().updateDisorderShapes();
                        editor.getView().getNode(item.id).getGraphics().updateCancerNameLabel();
                    }
                });
                //近亲，调解出现样式跳行问题chen.yuguo end
                if (typeof callback == "function")
                    callback();
            },
            error: function() {
                if (typeof genetic_syndrome_window != "undefined")
                    genetic_syndrome_window.close();
            },
            crossDomain: true
        });
        backgroundParent.insertBefore(background, backgroundPosition);
    },
    save: function() {
        if (this._saveInProgress)
            return;
        editor.getView().unmarkAll();
        var me = this;

        me._notSaved = true;
        var jsonData = this.serialize();
        var exportFamilyData = PedigreeExport.exportAsSimpleJSON(editor.getGraph().DG, "all");
        var familyDataToSave = {};
        familyDataToSave.family_data = exportFamilyData;
        familyDataToSave.image_data = editor.getWorkspace().getSVGCopy().getSVGText();
        console.log("[SAVE] jsonData: " + stringifyObject(jsonData));
        console.log("[SAVE] exportFamilyData: " + exportFamilyData);
        console.log(familyDataToSave);

        var image = $('canvas');
        var background = image.getElementsByClassName('panning-background')[0];
        var backgroundPosition = background.nextSibling;
        var backgroundParent = background.parentNode;
        backgroundParent.removeChild(background);
        var bbox = image.down().getBBox();
        var svg = editor.getWorkspace().getSVGCopy();
        var svgText = svg.getSVGText();
        debugger;
        var familyServiceURL = editor.getExternalEndpoint().getSavePedigreeURL();
        /*edit by lizhen 22018-08-07*/
        var param = {
            familyDiagram: JSON.parse(exportFamilyData),
            familyTreeId: parent.$("#familyTreeId").val(),
            userId: String(getCookie("userid")),
            patientid: parent.$("#patientId").val()
        };
        jQuery.ajax({
            // url:"http://10.131.101.207:8083/2.0/family/familyDiagram/saveOrUpdate",
            url: "http://10.131.101.142:8082/2.0/family/familyDiagram/saveOrUpdate",
            // url: "http://14.18.33.32:8082/2.0/family/familyDiagram/saveOrUpdate",
            // url: "http://10.10.30.28:8082/2.0/family/familyDiagram/saveOrUpdate",
            // url: "http://192.168.165.65:8082/2.0/family/familyDiagram/saveOrUpdate",
            // url: "http://192.168.165.63:8082/2.0/family/familyDiagram/saveOrUpdate",
            type: "POST",
            dataType: "json",
            data: JSON.stringify(param),
            contentType: "application/json",
            headers: { 'Authorization': getCookie("token") },
            success: function(data) {
                if (data.returnCode == 0 || data.returnCode == 200) {
                    editor.getActionStack().setSaveData();
                    jQuery("#viewriskreport_button").removeAttr("disabled");
                    jQuery("#viewriskreport_button").removeAttr("attr");
                    alert("保存成功！");
                } else {
                    alert(data.msg);
                }
            },
        });
        /*edit by lizhen 22018-08-07 end*/

        // jQuery.ajax({
        // 	url:save_url,
        // 	type:"post",
        // 	data:familyDataToSave,
        // 	success:function(res){
        // 		console.log(res);
        // 		alert("保存成功！");
        //         jQuery.each(res.data,function (index, item) {
        //             var node = editor.getView().getNode(item.id);
        //             node.setMemberID(item.memberID);
        //             console.log('set node:'+item.id+' member_id as:'+item.memberID);
        //             console.log(node);
        //             node=editor.getGraph().getProperties(item.id);
        //             node.memberID=item.memberID;
        //             editor.getGraph().setProperties(item.id,node);
        //         });
        //        //近亲，调解出现样式跳行问题chen.yuguo start
        //         jsonStr = JSON.parse( exportFamilyData );
        //         jQuery.each(jsonStr,function (index, item) {//console.log(item);return false;
        //             //名字
        //             firstName = item.firstName;
        //             if(firstName!=undefined){
        //                 if(firstName!==''){
        //                     editor.getView().getNode(item.id).getGraphics().updateNameLabel();
        //                 }
        //             }
        //             //结果评估
        //             evaluatedinfo = item.evaluatedinfo;
        //             if(evaluatedinfo!=undefined){
        //                 if(evaluatedinfo!==''){
        //                     editor.getView().getNode(item.id).getGraphics().updateEvaluatedInfoLabel();
        //                 }
        //             }
        //             //备注
        //             comments = item.comments;
        //             if(comments!=undefined){
        //                 if(comments!==''){
        //                     editor.getView().getNode(item.id).getGraphics().updateCommentsLabel();
        //                 }
        //             }
        //             //癌症：cancerTypes
        //             cancerTypes = item.cancerTypes;
        //             if(cancerTypes!=undefined){
        //                 editor.getView().getNode(item.id).getGraphics().updateDisorderShapes();
        //                 editor.getView().getNode(item.id).getGraphics().updateCancerNameLabel();  
        //             }
        //         });
        //          //近亲，调解出现样式跳行问题chen.yuguo end
        // 	},

        // 	crossDomain:true
        // });
        backgroundParent.insertBefore(background, backgroundPosition);
    },

    load: function() {
        console.log("initiating load process");
        var jsonData = [{ "id": 0, "memberID": 14218, "externalID": "20180712a", "firstName": "ar", "father": null, "mother": null, "sex": "male", "gender": "M", "curentAge": 0, "telNum": "122211", "bornAddr": "", "ethnicityName": "", "deathAge": 0, "deceasedText": "", "dateOfAdd": "2018-07-24", "precursor": 0, "comments": "bbb", "cancerAgeNum": null, "highRelativeCancerName": "乳腺癌", "urogenitalTumorName": null, "gastrointestinalTumorName": null, "otherTumorName": null, "rareTumorName": null, "childlessStatus": "infertile", "childlessReason": null, "disorders": ["卵巢癌", "乳腺癌"], "evaluatedinfo": "aaa", "carrierStatus": "affected", "cancer": [{ "id": "卵巢癌", "name": "卵巢癌", "age": null, "ageType": "", "bPart": "" }, { "id": "乳腺癌", "name": "乳腺癌", "age": null, "ageType": "", "bPart": "" }], "probability": [] }];
        jsonData = editor.getVersionUpdater().updateToCurrentVersion(jsonData);
        this.createGraphFromSerializedData(jsonData);

        /**lizhen  edit  2018-07-30 整合**/

        // new Ajax.Request(XWiki.currentDocument.getRestURL('objects/PhenoTips.PedigreeClass/0.xml').substring(1), {
        //     method: 'GET',
        //     onCreate: function() {
        //         document.fire("pedigree:load:start");
        //     },
        //     onSuccess: function (response) {
        //         var rawdata  = getSubSelectorTextFromXML(response.responseXML, "property", "name", "data", "value");
        //         var jsonData = unescapeRestData(rawdata);
        //         if (jsonData.trim()) {
        //             console.log("[LOAD] recived JSON: " + stringifyObject(jsonData));

        //             jsonData = editor.getVersionUpdater().updateToCurrentVersion(jsonData);

        //             this.createGraphFromSerializedData(jsonData);
        //         } else {
        //             new TemplateSelector(true);
        //         }
        //     }.bind(this)
        // })
    }
});